<template>
  <div class="reds-modal login-modal" role="presentation">
    <i tabindex="-1" class="reds-mask" aria-label="弹窗遮罩"></i>
    <div class="login-container">
      <div class="icon-btn-wrapper close-button" @click="close">
        <Close style="width: 1em; height: 1em" />
      </div>
      <div class="left">
        <img class="logo" src="@/assets/logo.png" />
      </div>
      <div class="right">
        <div class="input-container">
          <el-menu :default-active="activeIndex" background-color="#d9f2fc" class="el-menu-demo custom-menu"
            mode="horizontal" @select="handleSelect">
            <template v-if="activeIndex !== '3'">
              <el-menu-item index="1">账号登录</el-menu-item>
              <el-menu-item index="2">手机登录</el-menu-item>
            </template>
            <template v-else>
              <el-menu-item index="3">账号注册</el-menu-item>
            </template>
          </el-menu>
          <div class="line"></div>
          <div class="loginInfo">
            <div v-if="activeIndex === '1'">
              <form @submit.native.prevent="handleLogin">
                <el-form :model="loginForm" ref="loginFormRef">
                  <el-form-item label="账号">
                    <el-input v-model="loginForm.username" placeholder="输入账号" size="large"></el-input>
                  </el-form-item>
                  <el-form-item label="密码">
                    <el-input type="password" v-model="loginForm.password" placeholder="输入密码" size="large"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" native-type="button" class="login-button"
                      @click="handleLogin">登录</el-button>
                  </el-form-item>
                </el-form>
              </form>
            </div>
            <div v-else-if="activeIndex === '2'">
              <form @submit.prevent="handlePhoneLogin">
                <el-form :model="phoneForm" ref="phoneFormRef">
                  <el-form-item label="手机号">
                    <el-input v-model="phoneForm.phone" placeholder="输入手机号" size="large"></el-input>
                  </el-form-item>
                  <el-form-item label="验证码">
                    <div class="verification-container">
                      <el-input v-model="phoneForm.code" placeholder="输入验证码" size="large"
                        class="verification-input"></el-input>
                      <el-button @click="getVerificationCode" type="primary" class="get-code-button">获取验证码</el-button>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" native-type="button" class="login-button"
                      @click="handlePhoneLogin">登录</el-button>
                  </el-form-item>
                </el-form>
              </form>
            </div>
            <div v-else-if="activeIndex === '3'">
              <form @submit.prevent="handleRegister">
                <el-form :model="registerForm" ref="registerFormRef">
                  <el-form-item label="账号">
                    <el-input v-model="registerForm.username" placeholder="输入账号" size="large"></el-input>
                  </el-form-item>
                  <el-form-item label="密码">
                    <el-input type="password" v-model="registerForm.password" placeholder="输入密码"
                      size="large"></el-input>
                  </el-form-item>
                  <el-form-item label="确认密码">
                    <el-input type="password" v-model="registerForm.confirmPassword" placeholder="输入密码"
                      size="large"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" native-type="button" class="login-button"
                      @click="handleRegister">注册</el-button>
                  </el-form-item>
                </el-form>
              </form>
            </div>
          </div>
          <div class="err-msg" v-if="errorMsg">{{ errorMsg }}</div>
        </div>
        <div class="agreements" v-if="activeIndex === '1' || activeIndex === '2'">
          <span class="agree-icon"></span>
          <label> 我已阅读并同意</label><a class="links" target="_blank"
            href="https://agree.xiaohongshu.com/h5/terms/ZXXY20220331001/-1">《用户协议》</a><a class="links" target="_blank"
            href="https://agree.xiaohongshu.com/h5/terms/ZXXY20220509001/-1">《隐私政策》</a><br /><a class="links"
            target="_blank" href="https://oa.xiaohongshu.com/h5/terms/ZXXY20220516001/-1"
            style="margin-left: 25px">《儿童/青少年个人信息保护规则》</a>
        </div>
        <div v-if="activeIndex === '1' || activeIndex === '2'">
          <div class="oauth-tip"><span>没有账号？<a href="#" @click.prevent="activeIndex = '3'">立即注册</a></span></div>
        </div>
        <div v-if="activeIndex === '3'">
          <div class="oauth-tip"><span><a href="#" @click.prevent="activeIndex = '1'">返回登录</a></span></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Close } from "@element-plus/icons-vue";
import { ref,watch, onMounted } from "vue";
import { login, register, requestVerificationCode, PhoneLogin} from "../api/user";
import { useUserStore } from "../stores/user"; 

onMounted(() => {
  userStore.loadToken();
  if (userStore.token) {
    emit("clickChild", false);
  }
});
const userStore = useUserStore();
const emit = defineEmits(["clickChild"]);
const close = () => {
  //传递给父组件
  emit("clickChild", false);
};
const activeIndex = ref('1'); // 当前激活的菜单项
const loginForm = ref({
  username: '',
  password: ''
})
const phoneForm = ref({
  phone: '',
  code: ''
});
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const errorMsg = ref("");

watch(activeIndex, () => {
  errorMsg.value = ''
})

const handleLogin = async () => {
  try {
    const res = await login(loginForm.value.username, loginForm.value.password);
    const response = res.data;

    console.log(response);
    if (response.code === 1) {
      userStore.setToken(response.data);
      close()
    } else if (response.code === 0) {
      errorMsg.value = response.msg; // 显示错误信息
    }
  } catch (error) {
    errorMsg.value = "服务器繁忙，请稍后重试";
  }
};
// 处理手机登录
const handlePhoneLogin = async () => {
  try {
    const res = await PhoneLogin(phoneForm.value.phone, phoneForm.value.code);
    const response = res.data;

    console.log(response);
    if (response.code === 1) {
      close()
    } else if (response.code === 0) {
      errorMsg.value = response.msg; // 显示错误信息
    }
  } catch (error) {
    errorMsg.value = "服务器繁忙，请稍后重试"; // 显示请求错误信息
  }
};

// 获取验证码
const getVerificationCode = async () => {
  try {
    console.log(typeof (phoneForm.value.phone), phoneForm.value.phone)
    const res = await requestVerificationCode(phoneForm.value.phone);
    const response = res.data;
    if (response.code === 1) {
      console.log("验证码已发送");
      phoneForm.value.code = response.data;
    } else {
      console.error(response.msg); // 显示未注册提示
    }
  } catch (error) {
    console.error("获取验证码失败:", error);
  }
};
// 处理菜单选择
const handleSelect = (key: string) => {
  activeIndex.value = key;
};

//注册
const handleRegister = async () => {
  try {
    if (registerForm.value.password !== registerForm.value.confirmPassword) {
      errorMsg.value = '两次密码不一致'
      return
    }
    const res = await register(registerForm.value.username, registerForm.value.password);
    const response = res.data;

    if (response.code === 1) {
      console.log("注册成功:", response.data);
      activeIndex.value = "1";
      loginForm.value.username = registerForm.value.username;
      loginForm.value.password = registerForm.value.password; // 确保密码也为空字符串
    } else if (response.code === 0) {
      errorMsg.value = response.msg; // 显示错误信息
    }
  } catch (error) {
    console.error("请求错误:", error);
    errorMsg.value = "服务器繁忙，请稍后重试"; // 显示请求错误信息
  }
};

</script>

<style lang="less" scoped>
a {
  text-decoration: none;
  background-color: transparent;
}

.login-modal {
  z-index: 100010;
  flex-direction: column;
}

.reds-modal {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000002;
  box-sizing: border-box;
  visibility: visible;
  opacity: 1;
  transition: opacity 0.2s, visibility 0.2s;

  .reds-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.25);
    z-index: -1;
  }

  .login-container {
    display: flex;
    position: relative;
    width: 800px;
    height: 480px;
    background:
      linear-gradient(rgba(230, 247, 255, 0.9), rgba(230, 247, 255, 0.7)),
      url('@/assets/background.png');
    background-size: cover;
    background-position: center;
    border-radius: 16px;
    box-shadow: 0 4px 32px rgba(0, 0, 0, 0.08), 0 1px 4px rgba(0, 0, 0, 0.04);
    transition: all 0.2s;

    .close-button {
      position: absolute;
      right: 20px;
      top: 20px;
      cursor: pointer;
      color: rgba(51, 51, 51, 0.8);
    }

    .left {
      width: 400px;
      display: flex;
      align-items: center;
      flex-direction: column;
      border-right: 1px solid rgba(0, 0, 0, 0.08);

      img {
        border-style: none;
      }

      .logo {
        margin-top: 84px;
        width: 300px;
        height: 300px;
        -webkit-user-select: none;
        user-select: none;
        pointer-events: none;
        filter: drop-shadow(0 0 8px rgba(0, 132, 255, 0.5));
      }
    }

    .right {
      width: 400px;
      display: flex;
      align-items: center;
      flex-direction: column;
      margin-top: 48px;

      .title {
        font-size: 18px;
        color: rgba(51, 51, 51, 0.8);
        font-weight: 600;
        line-height: 120%;
      }

      .input-container {
        margin-top: 24px;
        width: 304px;
        display: flex;
        flex-direction: column;

        .auth-code {
          justify-content: center;
        }

        .auth-code,
        .phone {
          display: flex;
          align-items: center;
          font-size: 16px;
          line-height: 22px;
          color: rgba(51, 51, 51, 0.8);
          height: 48px;
          background: #fff;
          border-radius: 999px;
          transition: border-color 0.2s;
          border-bottom: 0.5px solid rgba(0, 0, 0, 0.08);

          .country-code {
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            width: 29px;
            height: 100%;
            font-weight: 400;
            margin-left: 16px;
            margin-right: 20px;
            color: #333;
          }

          .country-code:after {
            position: absolute;
            left: 41px;
            content: "";
            height: 24px;
            width: 1px;
            background-color: #fff;
          }
        }

        .auth-code input,
        .phone input {
          font-size: 16px;
          width: 130px;
          height: 100%;
          caret-color: #ff2442;
          color: #333;
        }

        .code-button {
          font-size: 16px;
          color: #ff2442;
          cursor: pointer;
          opacity: 0.5;
        }

        .err-msg {
          margin-top: 9.5px;
          height: 10px;
          line-height: 10px;
          color: var(--color-red);
          font-size: 14px;
          font-weight: 400;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .submit {
          margin-top: 24px;
          height: 48px;
          background: #ff2442;
          color: #fff;
          opacity: 0.5;
          border-radius: 999px;
          font-size: 16px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.2s;
          width: 100%;
        }

        form {
          display: block;
          margin-top: 0em;
        }
      }

      .agreements {
        width: 280px;
        position: relative;
        margin-top: 16px;
        padding-left: 18px;
        font-size: 12px;
        color: var(--color-tertiary-label);
        line-height: 120%;

        .agree-icon {
          display: inline-block;
          width: 10px;
          height: 10px;
          border-radius: 100%;
          background-color: #fff;
          border: 1px solid rgba(0, 0, 0, 0.183);
        }

        a {
          color: #13386c;
        }

        .links {
          font-weight: 400;
        }
      }

      .oauth-tip:after,
      .oauth-tip:before {
        display: block;
        width: 133px;
        height: 1px;
        content: "";
        background-color: rgba(0, 0, 0, 0.08);
      }

      .oauth-tip-line {
        margin: 0 12px;
      }

      .oauth-tip {
        margin-top: 29px;
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 14px;
        color: rgba(51, 51, 51, 0.6);
      }
    }
  }

  .verification-container {
    display: flex;
    align-items: center;

    .verification-input {
      flex: 1;
      /* 使输入框占据剩余空间 */
      margin-right: 10px;
      /* 输入框与按钮之间的间距 */
    }

    .get-code-button {
      flex-shrink: 0;
      /* 防止按钮缩小 */
    }
  }

  .login-button {
    width: 50%;
    /* 使登录按钮宽度占满 */
    padding: 10px;
    /* 增加按钮的内边距 */
    margin: 0 auto;
    /* 居中显示按钮 */
  }

  .loginInfo {
    display: flex;
    margin-top: 20px;
  }

  ::v-deep(.custom-menu) {
    background-color: transparent !important;
    --el-menu-text-color: black !important;
    box-shadow: none;
  }

  ::v-deep(.custom-menu .el-menu-item:hover) {
    background-color: #e6f7ff !important; // 浅蓝色
  }
}
</style>
